import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFileManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;


public class howayAction extends AnAction {

    private String accessPath = "";

    @Override
    public void actionPerformed(AnActionEvent e) {
        Project project = e.getProject();

        if(project != null){
            String basePath = project.getBasePath();
            assert basePath != null;
            File dir = new File(basePath);
            String processorDir = "";
            for(File f : Objects.requireNonNull(dir.listFiles())){
                if(!f.isFile() && f.getName().contains("processor")){
                    processorDir = f.getName();
                }
            }
            readAccess(dir);
            String packageName = Messages.showInputDialog(project,"Enter a package name:",
                    "Package Name", Messages.getInformationIcon());
            String path = basePath + "/" + processorDir + "/src/main/java/cn/ihoway/" + packageName;
            File pakageDir = new File(path);
            if(!pakageDir.exists()){
                pakageDir.mkdir();
                File ioDir = new File(path+"/io");
                ioDir.mkdir();
            }
            String prefix = Messages.showInputDialog(project,"Enter a prefix:",
                    "Prefix", Messages.getInformationIcon());
            String serviceId = Messages.showInputDialog(project,"Enter a service id:",
                    "Service Id", Messages.getInformationIcon());
            String inputPath = path + "/io/" + prefix + "Input.java";
            String outputPath = path + "/io/" + prefix + "Output.java";
            String processorPath = path + "/" + prefix + "Processor.java";
            write(inputPath,inputGenerator(packageName,prefix));
            write(processorPath,processorGenerator(packageName,prefix));
            write(outputPath,outputGenerator(packageName,prefix));
            String inputPackageName = "cn.ihoway."+ packageName +".io."+ prefix + "Input";
            String outputPackageName = "cn.ihoway."+ packageName +".io."+ prefix + "Output";
            String processorPackageName = "cn.ihoway."+ packageName +"."+ prefix + "Processor";
            readAndWrite(accessPath,serviceId,inputPackageName,outputPackageName,processorPackageName);
            VirtualFileManager.getInstance().refreshWithoutFileWatcher(true);
        }

    }

    private void readAccess(File dir){
        if(!dir.isFile()){
            for(File f : Objects.requireNonNull(dir.listFiles())){
                if(f.isFile()){
                    if("access.xml".equals(f.getName())){
                        accessPath = f.getAbsolutePath();
                    }
                }else {
                    //去掉target目录
                    if(!"target".equals(f.getName())){
                        readAccess(f);
                    }
                }
            }
        }
    }

    private void readAndWrite(String path,String serviceId,String inputPackageName,String outputPackageName,String processorPackageName){
        System.out.println(path);
        try {
            BufferedReader br = new BufferedReader(new FileReader(path,StandardCharsets.UTF_8));
            String content = "";
            String line;
            while ((line = br.readLine()) != null) {
                content += line + "\r\n";
            }
            String newLine = "\t<!--  -->\r\n\t<howay:service id=\"" + serviceId+ "\" processor=\""+ processorPackageName +"\" " +
                    "\r\n\t\t\t\tinput=\"" + inputPackageName + "\" output=\"" + outputPackageName + "\"/>";
            content = content.replaceAll("</access>",newLine + "\r\n\r\n</access>");
            write(path,content);
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void write(String path,String content){
        try {
            FileOutputStream out = new FileOutputStream(path);
            out.write(content.getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        } catch (IOException fileNotFoundException) {
            fileNotFoundException.printStackTrace();
        }
    }

    private String inputGenerator(String packageName,String prefix){
        return "package cn.ihoway."+ packageName +".io;\n" +
                "\n" +
                "import cn.ihoway.annotation.InputCheck;\n" +
                "import cn.ihoway.annotation.InsideCheck;\n" +
                "import cn.ihoway.common.CommonSeria;\n" +
                "import cn.ihoway.common.io.CommonInput;\n" +
                "\n" +
                "@InputCheck(check = true)\n" +
                "public class "+ prefix +"Input extends CommonInput {\n" +
                "    public InChomm inChomm = new InChomm();\n" +
                "\n" +
                "    @InputCheck(check = true)\n" +
                "    public static class InChomm extends CommonSeria {\n" +
                "\n" +
                "    }\n" +
                "}\n";
    }

    private String outputGenerator(String packageName,String prefix){
        return "package cn.ihoway."+ packageName +".io;\n" +
                "\n" +
                "import cn.ihoway.common.io.CommonOutput;\n" +
                "\n" +
                "public class "+ prefix +"Output extends CommonOutput {\n" +
                "}\n";
    }

    private String processorGenerator(String packageName,String prefix){
        return "package cn.ihoway."+ packageName +";\n" +
                "\n" +
                "import cn.ihoway.annotation.Processor;\n" +
                "import cn.ihoway.common.CommonProcessor;\n" +
                "import cn.ihoway."+ packageName +".io."+ prefix + "Input;\n" +
                "import cn.ihoway."+ packageName +".io."+ prefix + "Output;\n" +
                "import cn.ihoway.type.AuthorityLevel;\n" +
                "import cn.ihoway.type.StatusCode;\n" +
                "import cn.ihoway.util.HowayLog;\n" +
                "import cn.ihoway.util.HowayResult;\n" +
                "\n" +
                "@Processor(name = \""+ prefix + "Processor\",certification = true,limitAuthority = AuthorityLevel.COMMONMEMBER)\n" +
                "public class "+ prefix + "Processor  extends CommonProcessor<"+ prefix + "Input, "+ prefix + "Output> {\n" +
                "    private final HowayLog logger = new HowayLog("+ prefix + "Processor.class);\n" +
                "\n" +
                "    @Override\n" +
                "    protected StatusCode dataCheck("+ prefix + "Input input){\n" +
                "        return StatusCode.SUCCESS;\n" +
                "    }\n" +
                "    \n" +
                "    @Override\n" +
                "    protected HowayResult process("+ prefix + "Input input, "+ prefix + "Output output) {\n" +
                "        return null;\n" +
                "    }\n" +
                "}";
    }


}
